package controller

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/mvc"
	"github.com/micro/go-micro/v2/client"
	"gomicro/formJsonMicro/fjmMessage"
	"gomicro/formJsonMicro/model"
)

var (
	cli fjmMessage.MemberService
)

func init(){
	cli = fjmMessage.NewMemberService("member_micro_service", client.DefaultClient)
}

type MemberMicroController struct{
    Ctx  iris.Context
}

func (c *MemberMicroController) PostMicroinsert() mvc.Result {

	name := c.Ctx.FormValue("name")
	info := c.Ctx.FormValue("info")
	fmt.Println(name)

	//var mb []*model.Member
	//if err := c.Ctx.ReadJSON(&mb); err == nil{
	//	fmt.Println(mb)
	//	if data, derr := json.Marshal(&mb); derr == nil{
	//		var fmrr = fjmMessage.MemberListResponseOrRequest{
	//			MemberListStr:string(data),
	//		}
	//		res, err := cli.InsertAll(context.TODO(), &fmrr)
	//		if err != nil {
	//			fmt.Println("调用服务端失败", err)
	//			return mvc.Response{
	//				Object : res,
	//			}
	//		}
	//
	//		return mvc.Response{
	//			Object : res,
	//		}
	//	}
	//}else{
	//	fmt.Println(err)
	//}
	//
	//return mvc.Response{
	//	Object : map[string]string{
	//		"message":"解析失败",
	//		"code":"400",
	//	},
	//}

	var fmrr = fjmMessage.MemberListResponseOrRequest{
		MemberListStr:info,
	}

	res, err := cli.InsertAll(context.TODO(), &fmrr)
	if err != nil {
		fmt.Println(err)
		return mvc.Response{
			Object : res,
		}
	}
	
	return mvc.Response{
        Object : res,
    }
}


func (c *MemberMicroController) PostMicroquery() mvc.Result {

	var em = fjmMessage.Empty{}

	res, err := cli.QueryAllInfo(context.TODO(), &em)
	if err != nil {
		fmt.Println(err)
		return mvc.Response{
			Object : map[string]string{
				"message":"调用方法失败",
				"code":"400",
			},
		}
	}

	var mmm []*model.Member
	if uerr := json.Unmarshal([]byte(res.MemberListStr), &mmm); uerr == nil{
		return mvc.Response{
			Object : mmm,
		}

	}else{
		return mvc.Response{
			Object : map[string]string{
				"message":"解析失败",
				"code":"400",
			},
		}
	}
}


